<template>
	<view class="text-image-editor">
		<block  v-for="(item,index) in textImageArr" :key="index">
			<view  class="block type-text" :data-index="index" v-if="item.type=='text'" @tap="setActiveBlock" :class="{active: activeBlockIndex == index}">
				<textarea
					:placeholder="textImageArr.length == 1 ? placeholder : ''" 
					:maxlength="maxlength" 
					:auto-height="true" 
					:value="item.data.text"
					@input="updateText" 
					:data-index="index" 
					>
				</textarea>
				<view class="actions" v-if="activeBlockIndex == index">
					<image class="append-text" src="/static/text.png" mode="aspectFit" @tap.stop="appendTextBlock(index)"/>
					<image class="append-image" src="/static/image.png" mode="aspectFit" @tap.stop="chooseImage"/>
					<image class="del" src="/static/delete.png" mode="aspectFit" @tap.stop="removeBlock(index)"/>
				</view>
			</view>
			<view class="block type-image" 
				v-else-if="item.type=='image'" 
				:data-index="index" @tap="setActiveBlock" 
				:class="{active: activeBlockIndex == index}">  
				<image class="img_com" :src="item.data.url" mode="widthFix"/>
				<view class="mask" :style="{opacity:'0.5'}"></view>
				<view class="actions" v-if="activeBlockIndex == index">
					<image class="append-text" src="/static/text.png" mode="aspectFit" @tap.stop="appendTextBlock(index)"/>
					<image class="append-image" src="/static/image.png" mode="aspectFit" @tap.stop="chooseImage"/>
					<image class="del" src="/static/delete.png" mode="aspectFit" @tap.stop="removeBlock(index)"/>
				</view>
			</view>
		</block>
	</view>
</template>

<script>
	export default {
		props: {
			maxlength: {
				type: Number,
				default: -1
			},
			type: {
				type: String,
				default: ""
			},
			propsPlaceholder:{
				//文本框默认的文字
				type: String,
				default: '写点什么吧...'
			},
		  propsTextImageArr: {
				type: Array,
				default () {
					return [];
				}
			},
		},
		data() {
			return {
				uploadProgress: "0%",
				activeBlockIndex: -1,
				textImageArr: this.$props.propsTextImageArr,
				placeholder: this.$props.propsPlaceholder,
			}
		},
		watch: {
			propsTextImageArr(newData, oldData) {
				this.textImageArr = newData
			},
			propsPlaceholder(n, o) {
				this.placeholder = n
			}
		},
		methods: {
			//提交数据
			submit () {
				return this.textImageArr;
			},
			//删除
			removeBlock (index) {
				console.log('removeBlock', index)
				uni.showModal({
					title: '提示',
					content: '确定要删除此内容块？',
					success: (res) => {
						if (res.confirm) {
							if (this.textImageArr.length == 1) {
								uni.showToast({
									title: '内容不要为空哦...',
									icon: 'none'
								})
								return
							}
							this.textImageArr.splice(index, 1)
						} 
					} 
				});
			},
			updateText(e) {
				console.log('updateText', e)
				this.textImageArr[e.currentTarget.dataset.index].data.text = e.detail.value
				this.$emit('updateTextImage', this.type, this.textImageArr)
			},
			setActiveBlock (e) {
				console.log('setActiveBlock, ', e)
				this.activeBlockIndex = parseInt(e.currentTarget.dataset.index)
				console.log('当前 index: ', this.activeBlockIndex)
			},
			appendEmptyTextBlock(index) {
				console.log('appendEmptyTextBlock', index)
				this.textImageArr.splice(index, 0, {type: 'text', data: {text: ''}})
				this.$emit('updateTextImage', this.type, this.textImageArr)
			},
			appendTextBlock(index) {
				console.log('appendTextBlock, index: ', index)
				let self = this;
				this.appendEmptyTextBlock(++index)
				setTimeout(function () {
					self.activeBlockIndex++
					console.log('当前 block 数量 ', self.textImageArr.length)
				}, 100)
			},
			appendImageBlock(data) {
				console.log('appendImageBlock: ', data)
				//注意，splice() 函数从索引+1开始
				let cursor = this.activeBlockIndex
				this.textImageArr.splice(++cursor, 0, {type: "image", data: data})
				this.$emit('updateTextImage', this.type, this.textImageArr)
			},
			chooseImage() {
				let self = this;
				uni.chooseImage({
					count: 1,
					sourceType: ['album'],
					async success(res) {
						console.log(`chooseImage success: `)
						console.log(res)
						let uploadTokenRes = await self.$api.uploadTokenCloudinary();
						if (uploadTokenRes.ret != 0) {
							uni.showToast({
								title: uploadTokenRes.msg
							})
							return
						}
						uni.showLoading({
							title: "上传中...",
							mask: true
						})
						const uploadTask = uni.uploadFile({
								url: uploadTokenRes.data.upload_url,
								filePath: res.tempFilePaths[0],
								name: 'file',
								formData: {
										'signature': uploadTokenRes.data.signature,
										'timestamp': uploadTokenRes.data.timestamp,
										'api_key': uploadTokenRes.data.api_key,
								},
								success: (uploadFileRes) => {
									console.log(uploadFileRes.data);
									let data = JSON.parse(uploadFileRes.data)
									self.appendImageBlock(data)
								},
								fail: (res) => {
									console.log("fail: ", res)
								},
								complete:() => {
									uni.hideLoading()
									uni.showToast({
										title: '上传完成！'
									})
								}
						});
		
						uploadTask.onProgressUpdate((res) => {
								console.log('上传进度: ' + res.progress);
								// console.log('已经上传的数据长度: ' + res.totalBytesSent);
								// console.log('预期需要上传的数据总长度: ' + res.totalBytesExpectedToSend);
								// uni.hideLoading()
								// uni.showLoading({
								// 	title: res.progress + "%"
								// })
								// 测试条件，取消上传任务。
								// if (res.progress > 50) {
								// 		uploadTask.abort();
								// }
						});
					}
				})
			}
		}
	}
</script>

<style lang="scss">

.text-image-editor {
	width: 100%;
	padding: 30upx 0;
	box-sizing: border-box; 
	padding-top: 10rpx;
	background: #fff;
	.type-text {
		padding-top: 20upx;
		padding-bottom: 80upx;
		width: 100%;
		font-size: 32upx;
		background: #fff;
		line-height: 1.5;
	}
	.add-image {
		margin-top: 20upx;
		width: 100upx;
		height: 100upx;
		color: #ddd;
		font-size: 100upx;
		line-height: 95%;
		text-align: center;
		background-color: #eee;
		cursor: pointer;
		border-radius: 10upx;
	}
	.active {
		border: 1px solid red;
	}
	.block {
		margin: 10upx 0;
		transition: border-color .2s;
		width: 100%;
		position: relative;
		.img_com {
			width: 100%;
		}
		.mask {
			background: rgba(0,0,0,0.5);
			position: absolute;
			left: 0;
			top: 0;
			width: 100%;
			height: 100%;
		}
		.actions {
			width: 100%;
			height: 60upx;
			position: absolute;
			bottom: 0;
			text-align: right;
			.del, .append-text, .append-image {
				height: 60upx;
				width: 60upx;
				margin-left: 20upx;
			}
		}
		uni-textarea {
			width: 100%;
			min-height: 100upx;
		}
	}
	
}
</style>
